/*
 * @Author: yangrongxin
 * @Date: 2021-08-09 17:01:13
 * @LastEditors: guoju
 * @LastEditTime: 2022-01-10 14:22:22
 */
import { useState, useEffect } from 'react';
import Taro from '@tarojs/taro';
import { Chart } from '@antv/f2/lib/core';
import '@antv/f2/lib/animation/animate'; // 引入动画插件
import '@antv/f2/lib/geom/area';
import '@antv/f2/lib/geom/line';
import '@antv/f2/lib/geom/point';
import '@antv/f2/lib/coord/polar';
import '@antv/f2/lib/component/guide/arc';
import '@antv/f2/lib/component/guide/index';
import '@antv/f2/lib/component/axis/circle';
import '@antv/f2/lib/geom/interval';
import Tooltip from '@antv/f2/lib/plugin/tooltip';
import Guide from '@antv/f2/lib/plugin/guide';
import F2Canvas from '../F2Component';
import styles from './index.module.less';

const CanvasCircle = (props) => {
  const { questionNum, curQuestionIndex } = props;

  const [size, setSize] = useState<any>({
    cWidth: '',
    cHeight: '',
  });

  const [charInstance, setCharInstance] = useState<any>();

  useEffect(() => {
    const sysInfo = Taro.getSystemInfoSync();
    let pixelRatio = 1;
    if (Taro.getEnv() === Taro.ENV_TYPE.ALIPAY) {
      pixelRatio = sysInfo.pixelRatio;
    }
    const cWidth = pixelRatio * sysInfo.windowWidth;
    const cHeight = (500 / 750) * cWidth;
    setSize({ cWidth, cHeight });
  }, []);

  useEffect(() => {
    const perPie = 100 / questionNum;
    charInstance?.changeData([
      {
        x: '1',
        y: perPie * curQuestionIndex,
      },
    ]);
  }, [questionNum, curQuestionIndex]);

  const onInit = (config) => {
    const perPie = 100 / questionNum;
    const data = [
      {
        x: '1',
        y: perPie * curQuestionIndex,
      },
    ];
    Chart.plugins.register([Tooltip, Guide]);
    const chart = new Chart(config);
    chart.source(data, {
      y: {
        max: 100,
        min: 0,
      },
    });
    chart.axis(false);
    chart.tooltip(false);
    chart.coord('polar', {
      transposed: true,
      innerRadius: 0.95,
      radius: 0.4,
    });
    chart
      .interval()
      .position('x*y')
      .color('#f7d314')
      .size(5)
      .animate({
        appear: {
          duration: 1200,
          easing: 'cubicIn',
        },
        update: {
          duration: 500,
          easing: 'cubicIn',
        },
      });
    chart.render();
    setCharInstance(chart);
    return chart;
  };

  const { cWidth, cHeight } = size;
  let canvasProps = {};
  if (Taro.getEnv() === Taro.ENV_TYPE.ALIPAY) {
    canvasProps = { width: cWidth, height: cHeight, style: { width: '100%', height: '100%' } };
  } else {
    canvasProps = { style: { width: cWidth, height: cHeight } };
  }
  return <F2Canvas {...canvasProps} className={styles.canvasEle} onInit={onInit} />;
};

export default CanvasCircle;
